/* eslint-disable react/no-array-index-key */
/* eslint-disable no-bitwise */
/**
 * 操作步骤
 * @param {} props
 */

import React, { useState } from 'react';
import { Steps, Row, Spin } from 'antd';
import BizIcon from '@/components/BizIcon';
import AuthComponent from '@/utils/auth/AuthComponent';
import { router, withRouter } from 'umi';
import { useRequest, defaultFormatResult } from '@/hooks';

import moment from 'moment';
import cn from 'classnames';
import { getDict, getDisplayText } from '@/utils/dataDictUtil';
import { CONTACT_WAY } from '../../dictionary';
import { queryResumeOperateListById } from '../../service';
import styles from './index.less';


const { Step } = Steps;
const emptyStr = '--';
// TODO 目前使用重写样式的方式，后续需优化
const TalentStatusStep = ({ location: { query }, talentId, refresh, onRefreshed }) => {
    const [blacklistBlockType, setBlacklistBlockType] = useState([]);
    React.useEffect(() => {
        // 加入黑名单获取
        getDict('blacklistBlockType').then(ret => setBlacklistBlockType(ret));
    }, []);
    const { data, run, loading } = useRequest(() => queryResumeOperateListById(talentId), {
        manual: true,
        ...defaultFormatResult
    });
    React.useEffect(() => {
        if (talentId) {
            run();
        }
    }, [talentId]);
    const [list, resumeStep] = React.useMemo(() => {
        const d = data || {};
        return [d.recruitResumeOperateRecordVOList || [], d.resumeStep || 0];
    }, [data]);
    const [expandArr, setExpandArr] = React.useState();
    React.useEffect(() => {
        if (!list.length) {
            setExpandArr([]);
        }
        setExpandArr(new Array(list.length).fill(false));
    }, [list]);
    React.useEffect(() => {
        if (refresh) {
            run();
            if (onRefreshed) onRefreshed();
        }
    }, [refresh]);
    if (loading) {
        return (
            <Row type="flex" justify="center" style={{ padding: 32 }}>
                <Spin />
            </Row>
        );
    }

    const renderOperateContent = (item, index) => {
        const { operateType, operateInfo, operateTime, operateDetail, operateContent, operateTail } = item;
        const info = operateInfo && JSON.parse(operateInfo);
        const renderBtn = () => {
            const renderExpandToggle = i => {
                const expandObj = expandArr[i];
                const text = expandObj ? '收起' : '展开';
                return (
                    <a
                        href="#"
                        className={styles.btn}
                        onClick={e => {
                            e.preventDefault()
                            setExpandArr(val => {
                                const ret = [...val];
                                ret.splice(i, 1, !expandObj);
                                return ret;
                            })
                        }}
                    >
                        {text}
                        <BizIcon type={expandObj ? 'fold_arrow_o' : 'unfold_arrow_o'} />
                    </a>
                );
            };
            const renderDetailBtn = (href, tab, authCode) => (
                <AuthComponent code={authCode}>
                    <a
                        href={href}
                        className={styles.btn}
                        onClick={() => {
                            history.push({
                                query: {
                                    ...query,
                                    activeKey: tab
                                }
                            });
                        }}
                    >
                        详情
                    </a>
                </AuthComponent>
            );

            // 联系面试---确认面试 contactRecordSaveDTO、 人事修改面试  候选人接受面试  提交面试准备 修改面试准备 提交面试记录 提交面试总结
            const detailOperateArr = [450, 481, 420, 490, 491, 492, 493];
            if (detailOperateArr.indexOf(operateType) !== -1) {
                const contractId = operateType === 450 ? info?.contactRecordSaveDTO?.contactId : info.contractId;
                return renderDetailBtn(
                    `${'#INTERVIEW_DETAIL-'}${contractId}`,
                    'INTERVIEW',
                    'office:recruitment:course:interview'
                );
            }
            // 候选人提交应聘登记表
            if (operateType === 310) {
                return renderDetailBtn('#', 'RESUME', 'office:recruitment:course:resume');
            }
            // 候选人请求修改面试时间、 联系面试--淘汰、推荐到其它岗位
            if (operateType === 453 || operateType === 451 || operateType === 422) {
                return renderExpandToggle(index);
            }
            // 803为加入黑名单，有拉黑原因，可以不需要理由描述
            if (!operateDetail && operateType !== 703) {
                return '';
            }
            return renderExpandToggle(index);
        };
        const renderDesc = () => {
            // 联系面试--淘汰、推荐到其它岗位
            if (operateType === 453 || operateType === 451) {
                const { contactRecordSaveDTO: { contactTime, contactDesc, contactWay } = {} } = info;
                const arr = [
                    {
                        label: '联系方式:',
                        value: getDisplayText(CONTACT_WAY, contactWay) || emptyStr
                    },
                    {
                        label: '联系时间:',
                        value: contactTime ? moment(contactTime).format('YYYY-MM-DD HH:mm') : emptyStr
                    },
                    {
                        label: '联系内容:',
                        value: contactDesc || emptyStr
                    }
                ];
                return (
                    <div className={styles.expandWrapper}>
                        {arr.map((_, i) => (
                            <>
                                <div className={styles.box} key={i}>
                                    <div className={styles.lighter}>{_.label}</div>
                                    <div className={styles.light} style={{ flex: 1, marginLeft: 4 }}>
                                        {_.value}
                                    </div>
                                </div>
                                {i !== arr.length - 1 && <div style={{ marginTop: 4 }} key={i}></div>}
                            </>
                        ))}
                    </div>
                );
            }
            // 候选人请求修改面试时间
            if (operateType === 422) {
                const { freeTimeList = [] } = info;
                const renderTimeRegion = (startTime, endTime) => {
                    if (!startTime || !endTime) {
                        return emptyStr;
                    }
                    return `${moment(startTime).format('YYYY-MM-DD HH:mm')}~${moment(endTime).format('HH:mm')}`;
                };
                return (
                    <div className={styles.expandWrapper}>
                        <div className={styles.lighter}>建议时间段:</div>
                        {freeTimeList.map((obj, i) => {
                            const { startTime, endTime } = obj;
                            return (
                                <div key={i} className={styles.light}>
                                    {renderTimeRegion(startTime, endTime)}
                                </div>
                            );
                        })}
                    </div>
                );
            }
            // 加入黑名单操作
            if (operateType === 703) {
                const { blockType } = info;
                const { text } = blacklistBlockType.find(v => v.value === blockType.toString()) || {};
                return <div className={styles.expandWrapper}>
                    <div className={styles.lighter}>拉黑原因:</div>
                    <div className={styles.light}>{text}</div>
                    {
                        operateDetail && <>
                            <div className={styles.lighter}>描述:</div>
                            <div className={styles.light}>{operateDetail}</div>
                        </>
                    }
                </div>
            }
            // 加入黑名单操作
            if (operateType === 704) {
                const { noticeEmployeeNames = [] } = info;
                return <div className={styles.expandWrapper}>
                    <div className={styles.lighter}>理由:</div>
                    <div className={styles.light}>{operateDetail}</div>
                    <div className={styles.lighter}>通知人员:</div>
                    <div className={styles.light}>{noticeEmployeeNames.join('、')}</div>
                </div>
            }
            return (
                <div className={styles.expandWrapper}>
                    {/* 推荐操作不显示理由是 */}
                    {operateType !== 404 && <div className={styles.lighter}>理由是:</div>}
                    <div className={styles.light}>{operateDetail}</div>
                </div>
            );
        };

        return (
            <div className={styles.content}>
                <div className={styles.box}>
                    <div className={cn(styles.time, styles.lighter)}>
                        {operateTime ? moment(operateTime).format('YYYY-MM-DD HH:mm') : ''}
                    </div>
                    {renderBtn(index)}
                </div>

                <div>{operateContent}</div>
                {expandArr[index] && renderDesc()}
                <div className={styles.lighter}>{operateTail}</div>
            </div>
        );
    };
    return (
        <div>
            <div className={styles.stepWrapper}>
                <Steps
                    current={(resumeStep - 1) | 0}
                    labelPlacement="vertical"
                    size="small"
                    className={styles.statusStep}
                >
                    <Step title="简历" />
                    <Step title="候选" />
                    <Step title="面试" />
                    <Step title="录用" />
                    <Step title="入职" />
                </Steps>
            </div>
            <div className={styles.operateWrapper}>
                {list.length > 0 && (
                    <Steps direction="vertical" size="small" progressDot>
                        {list.map((item, index) => (
                            <Step status="process" key={index} title={renderOperateContent(item, index)}></Step>
                        ))}
                    </Steps>
                )}
            </div>
        </div>
    );
};

export default withRouter(TalentStatusStep);
